package com.dong.cutesms.components;

import com.dong.cutesms.R;
import com.dong.cutesms.activitys.MainActivity;
import com.dong.cutesms.constant.AppConstant;
import com.dong.cutesms.constant.AppParameters;
import com.dong.cutesms.utils.SmsUtils;

import android.app.Dialog;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;

public class DialogChooseAvatar {
	private Context context;
	private Dialog dialog;
	SmsUtils smsUtils;
	public DialogChooseAvatar(Context _context){
		this.context = _context;
		dialog = new Dialog(context);
		smsUtils = new SmsUtils(context.getContentResolver(), context);
		dialog.setContentView(R.layout.dialog_choose_avatar);
		GridView grid = (GridView) dialog.findViewById(R.id.grid_avatar);
		grid.setAdapter(new GridAvatarAdaper(context));
		dialog.getWindow().setBackgroundDrawable(
				new ColorDrawable(Color.TRANSPARENT));
		dialog.show();
	}

	public Dialog getInstance(){
		return dialog;
	}
	
	private class GridAvatarAdaper extends BaseAdapter{
		LayoutInflater inflater;
		ViewHolder viewHolder;
		public GridAvatarAdaper(Context context){
			inflater = LayoutInflater.from(context);
		}
		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return AppConstant.listAvatar.length;
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public View getView(final int position, View convertView, ViewGroup arg2) {
			// TODO Auto-generated method stub
			if (convertView == null) {

				convertView = inflater.inflate(R.layout.dialog_choose_avatar_item, null);
				viewHolder = new ViewHolder();
				
				viewHolder.icon = (ImageView) convertView.findViewById(R.id.tv_choose_avatar);
				convertView.setTag(viewHolder);

			} else {
				viewHolder = (ViewHolder) convertView.getTag();
			}
			viewHolder.icon.setImageResource(AppConstant.listAvatar[position]);
			
			viewHolder.icon.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View arg0) {
					
					dialog.dismiss();
					int avatarID = AppConstant.listAvatar[position];
					smsUtils.changeAvatar(AppParameters.people,avatarID);
					MainActivity.adapter.notifyDataSetChanged();
				}
			});
			
			return convertView;
		}
		
	}
	private class ViewHolder {
		ImageView icon;
		
	}
}	

